package com.texas_android.app.http;

import android.app.Application;
import android.text.TextUtils;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.texas_android.app.Appconfig.AppConfig;
import com.texas_android.app.utils.Logger;


/**
 * Created by solin on 2017/4/26.
 */

public class ApiHttpClient {
    public static String HOST = AppConfig.HOST;
    private static String API_URL = HOST + "%s";
    private static AsyncHttpClient CLIENT;

    public ApiHttpClient() {
    }

    /**
     * 初始化网络请求，包含Cookie的初始化
     *
     * @param context
     */
    public static void init(Application context) {
        CLIENT = null;
        AsyncHttpClient client = new AsyncHttpClient();
        ApiHttpClient.setHttpClient(client, context);
        setCookieHeader("");
    }

    public static void setHttpClient(AsyncHttpClient c, Application application) {
        CLIENT = c;
        initSSL(CLIENT);
    }

    private static void initSSL(AsyncHttpClient client) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setCookieHeader(String cookie) {
        if (!TextUtils.isEmpty(cookie)) {
            CLIENT.addHeader("Cookie", cookie);
        }
        Logger.log("Cookie:" + cookie);
    }

    /**
     * 返回网络请求的路径
     *
     * @param partUrl
     * @return
     */
    public static String getAbsoluteApiUrl(String partUrl) {
        String url = partUrl;
        if (AppConfig.DEBUG) {
            //手动切换测试服务器
        }
        if (!partUrl.startsWith("http:") && !partUrl.startsWith("https:")) {
            url = String.format(API_URL, partUrl);
        }
        return url;
    }

    public static void get(String partUrl, RequestParams params, AsyncHttpResponseHandler handler) {

        params.put("", "");//公共参数
        CLIENT.get(getAbsoluteApiUrl(partUrl), params, handler);
        Logger.log("GET" + partUrl + "?" + params);
    }

    public static void post(String partUrl, RequestParams params, AsyncHttpResponseHandler mhandler) {
        if (params != null) {
            params.setContentEncoding("utf-8");
        }

        CLIENT.post(getAbsoluteApiUrl(partUrl), params, mhandler);
        Logger.log("POST:" + getAbsoluteApiUrl(partUrl) + "?" + params);
    }
}
